<?php

namespace app\controller;

use think\facade\Cache;
use app\lib\Key;

/**
 * 支付pay 服务 鉴权API
 */
class AuthBase extends ApiBase {

    public $appId = '';
    public $token = '';
    public $time = 0;
    public $userId = 0;

    public function initialize() {
        parent::initialize();
        $this->appId = input('param.appid', '', 'trim');
        $this->token = input('param.token', '', 'trim');
        $this->time = input('param.time', 0, 'intval');
        $this->userId = input('param.user_id', 0, 'intval');
        // 参数校验
        $data = [
            'appid'   => $this->appId,
            'token'   => $this->token,
            'time'    => $this->time,
            'user_id' => $this->userId,
        ];
        $validate = new \app\validate\Pay();
        if (!$validate->check($data)) {
            $this->show($validate->getError());
        }
        $this->checkAuth();
    }

    /**
     * api-token校验
     * app_id:
     * app_key:
     * access_token:
     * post请求
     */
    public function checkAuth() {
        $app = config("appuser.{$this->appId}");
        if (!$app) {
            $this->show('不存在该appid，请联系支付平台负责人申请开通', ['appid' => $this->appId]);
        }

        $data = [
            $this->time,
            $this->appId,
            $app['key'],
        ];

        // 时间检验
        if ($app['expire'] + $this->time < time()) {
            $this->show('请求token时间已过期，请重新生成token');
        }
        // token检验
        $token = md5(implode($app['stitching_symbol'], $data));
        if ($this->token != $token) {
            $this->show('不合法的请求，请检验token是否合法');
        }

        // token只能用一次
        $token_key = Key::Order($this->appId) . '_' . $token;
        if (Cache::store('redis')->get($token_key)) {
            $this->show("token已经使用，请重新尝试");
        }
        Cache::store('redis')->set($token_key, 1, $app['expire']);
        // 使用https
        return true;
    }
}
